package rabbitMqLearn.mq.acquaintance;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory factory = new ConnectionFactory();
        //登录到mq
        factory.setHost("127.0.0.1");
        factory.setPort(15672);
        factory.setVirtualHost("learn");

        factory.setUsername("learner");
        factory.setPassword("learner");
        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();

        channel.queueDeclare("learn", false, true, false, null);

        DefaultConsumer consumer = new DefaultConsumer(channel) {
            /**
             * @param consumerTag 消费者标签
             * @param envelope 消息的封包消息 交换机 队列名称
             * @param properties 配置信息
             * @param body the message body (opaque, client-specific byte array)
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) {
                String message = new String(body);
                System.out.println("消费者收到消息: " + message);
            }
        };
        /**
         * String queue, 队列名称
         * boolean autoAck, 自动确认
         * Consumer callback 回调函数 收到消息处理的逻辑
         */
        channel.basicConsume("learn", true, consumer);

        TimeUnit.SECONDS.sleep(5);
        channel.close();
        connection.close();
    }


}
